;
(function () {
  new Vue({
    el: '#finicial_voucher_rule_config_two',
    data: {
      bizCategoryCode: null,
      bizCategoryName: null,
      bizTypeName: null,
      accountingId: null,
      voucherRulesId: null,
      voucherRules: [],
      accountingLists: [],
      selectedVocherRuleState: ['Y'],
      radioData: [{
        'name': '启用',
        'code': 'Y'
      }, {
        'name': '停用',
        'code': 'N'
      }],
      selectedExpense: [],
      totalExpense: [],
      concatExpenseData: [],
      reversalRuleData: [],
      selectedReversalRule: [],
      vocherTypeData: [],
      summaryData: [],
      accountingData: [],
      lendData: [],
      ruleData: [],
      // 凭证所选的code信息
      selectedVocherData: [{
        voucherTypeId: [],
        voucherDetails: [{
          // summarays: [{
          //   summaryCode: [],
          //   summaryValue: '',
          // }], 
          summarayIds: [], //摘要
          subjectId: [], //会计科目id
          fzhsText: '', //辅助核算文本
          borrowAmountRuleCode: [], // 借方金额规则字典code(借方)
          loanAmountRuleCode: [], // 贷方金额规则字典code(借方)
          superpositionRule: [], //金额叠加规则，PLUS正向(加)，MINUS逆向(减)
        }]

      }],
      // 凭证的全部信息
      allVocherData: [{
        'borrowSummary': {},
        'rentSummary': {}
      }],
      ops: {
        bar: {
          background: '#c1c1c1'
        }
      },
      dictList: [],
      selectedScene: [],
      standardList: [], //业务标准列表
      standardActive: [], //选中业务标准的code
    },
    created() {
      this.bizCategoryCode = hlUrlUtil.GetQueryString('bizCategoryCode')
      this.bizCategoryName = hlUrlUtil.GetQueryString('bizCategoryName')
      this.accountingId = hlUrlUtil.GetQueryString('accountId')
      this.voucherRulesId = window.localStorage.getItem('voucherRulesId')
    },
    mounted() {
      if (this.bizCategoryCode == 'SKYW' || this.bizCategoryCode == 'SRQR') {
        this.getScene()
        if (this.bizCategoryCode == 'SKYW') {
          this.getStandard()
        }
      } else {
        this.asyncGetVoucherRuleDetails()
      }
    },
    methods: {
      // 获取场景类型
      getScene() {
        hlhttp.get({
          url: 'configure/dict',
          data: {
            'module_code': 'CIWU',
            'config_name': 'CW_VOUCHER_SCENE_TYPE',
            'parent_dict_code': this.bizCategoryCode
          },
          success: res => {
            res.map(item => {
              item.name = item.dictName
              item.code = item.dictCode
            })
            this.dictList = res
            this.asyncGetVoucherRuleDetails()
          }
        })
      },
      // 获取业务标准
      getStandard() {
        hlhttp.get({
          url: 'configure/dict',
          data: {
            'module_code': 'CIWU',
            'config_name': 'CW_VOUCHER_BIZ_STANDARD',
          },
          success: res => {
            res.map(item => {
              item.name = item.dictName
              item.code = item.dictCode
            })
            this.standardList = res
          }
        })
      },
      asyncGetVoucherRuleDetails() {
        this.getVoucherRulesData()
        this.getReversalRuleData()
        this.getExpense()
        this.getVocherTypeData()
        this.getVoucherRuleSummary()
        this.getAccountingSubjects()
        this.getlendData()
        this.getVoucherRuleAmountRule()

        this.getVoucherRuleDetails()
      },
      // 获取凭证规则下的业务类型（左侧栏）
      getVoucherRulesData() {
        var self = this
        hlhttp.get({
          url: 'acct/voucher_rules',
          data: {
            'accounting_id': self.accountingId
          },
          success(data) {
            self.voucherRules = data
          }
        })
      },
      // 点击左侧栏
      selectSecondMenu(id, code) {
        this.voucherRulesId = id
        this.bizCategoryCode = code
        this.getlendData()
        this.getExpense()
        this.getScene()
        this.getVoucherRuleDetails()
      },
      // 获取冲销规则字典
      getReversalRuleData() {
        var self = this
        hlhttp.get({
          url: 'configure/dict',
          data: {
            'module_code': 'CIWU',
            'config_name': 'CW_VOUCHER_OFFSET_RULE'
          },
          success(data) {
            let tmpArr = []
            data.forEach(el => {
              tmpArr.push({
                'name': el.dictName,
                'code': el.dictCode
              })
            })
            self.reversalRuleData = tmpArr
          }
        })
      },
      // 获取关联费项下拉列表
      getExpense() {
        var self = this
        self.concatExpenseData = []
        hlhttp.get({
          url: 'voucher/expenditures',
          data: {
            'biz_type': self.bizCategoryCode
          },
          success(data) {
            data.forEach(el => {
              let tmpArr = []
              el.expenditures.forEach((el1, ix1) => {
                // 如果数据存在 id 则保留id 不存在 id 则随机生成一个id
                const id = el1.expenditureId ? el1.expenditureId : (parseInt(new Date().getTime() / 1000) + ix1) + ''
                tmpArr.push({
                  'name': el1.expenditureName,
                  'type': el1.expenditureType,
                  'code': id
                })
              })
              self.concatExpenseData.push({
                'name': el.expenditureTypeName,
                'type': el.expenditureType,
                'children': tmpArr
              })
            })
          }
        })
      },
      // 获取凭证类别
      getVocherTypeData() {
        var self = this
        hlhttp.get({
          url: 'acct/voucher_types',
          data: {
            'accounting_id': self.accountingId
          },
          success(data) {
            let tmpArr = []
            data.forEach(el => {
              tmpArr.push({
                'name': el.name,
                'code': el.id
              })
            })
            self.vocherTypeData = tmpArr
          }
        })
      },
      // 获取摘要字典
      getVoucherRuleSummary() {
        var self = this
        hlhttp.get({
          url: 'configure/dict',
          data: {
            'module_code': 'CIWU',
            'config_name': 'CW_VOUCHER_SUMMARY_RULE_CONFIG_ITEM'
          },
          success(data) {
            let tmpArr = []
            data.forEach(el => {
              tmpArr.push({
                'name': el.dictName,
                'code': el.dictCode
              })
            })
            self.summaryData = tmpArr
          }
        })
      },
      // 获取会计科目下拉列表
      getAccountingSubjects() {
        var self = this
        hlhttp.get({
          url: 'acct/accounting_subjects',
          data: {
            'accounting_id': self.accountingId
          },
          success(data) {
            let tmpArr = []
            data.forEach(el => {
              tmpArr.push({
                'name': el.name,
                'code': el.id
              })
            })
            self.accountingData = tmpArr
          }
        })
      },
      // 获取借方贷方下拉列表
      getlendData() {
        var self = this
        hlhttp.get({
          url: 'configure/dict',
          data: {
            'module_code': 'CIWU',
            'config_name': 'CW_VOUCHER_TRADE_AMOUNT_RULE',
            'parent_dict_code': self.bizCategoryCode
          },
          success(data) {
            let tmpArr = []
            data.forEach(el => {
              tmpArr.push({
                'name': el.dictName,
                'code': el.dictCode
              })
            })
            self.lendData = tmpArr
          }
        })
      },
      // 获取金额正负规则下拉列表
      getVoucherRuleAmountRule() {
        var self = this
        hlhttp.get({
          url: 'configure/dict',
          data: {
            'module_code': 'CIWU',
            'config_name': 'CW_VOUCHER_SUPERPOSITION_RULE'
          },
          success(data) {
            let tmpArr = []
            data.forEach(el => {
              tmpArr.push({
                'name': el.dictName,
                'code': el.dictCode
              })
            })
            self.ruleData = tmpArr
          }
        })
      },
      // 获取凭证规则详情
      getVoucherRuleDetails() {
        if (this.voucherRulesId == null || this.voucherRulesId == 'null') {
          if (this.dictList.length) {
            this.selectedScene = this.dictList.length ? [this.dictList[0].code] : []
          }
          return
        }
        hlhttp.get({
          url: 'acct/voucher_rule',
          data: {
            'id': this.voucherRulesId
          },
          success: data => {
            this.voucherRulesId = data.id
            this.bizCategoryCode = data.bizCategoryCode
            this.bizCategoryName = data.bizCategoryName

            // 业务标准
            this.standardActive = data.bizStandardCode ? [data.bizStandardCode] : []

            this.bizTypeName = data.bizTypeName
            this.selectedVocherRuleState = data.status.split()
            if (!data.sceneTypeCode) {
              this.selectedScene = this.dictList.length ? [this.dictList[0].code] : []
            } else {
              this.selectedScene = [data.sceneTypeCode]
            }
            this.selectedReversalRule = data.offsetRuleCode.split()
            // 费项
            let tmpExpense = [],
              totalExpense = []
            if (data.expenses.length) {
              data.expenses.forEach(el => {
                tmpExpense.push(el.expenditureId)
                totalExpense.push({
                  'expenditure_id': el.expenditureId,
                  'expenditure_name': el.expenditureName,
                  'expenditure_type': el.expenditureType
                })
              })
            }
            this.selectedExpense = tmpExpense
            this.totalExpense = totalExpense
            // 凭证类型
            if (data.details.length) {
              this.selectedVocherData = []
              let obj = {
                voucherTypeId: [],
                voucherDetails: []
              }
              data.details.map(item => {
                obj.voucherTypeId = [item.voucherTypeId]
                let detail = {
                  summarayIds: [],
                  subjectId: [item.subjectId],
                  fzhsText: this.getAssistsText(item.assists),
                  borrowAmountRuleCode: [item.borrowAmountRuleCode],
                  loanAmountRuleCode: [item.loanAmountRuleCode],
                  superpositionRule: [item.superpositionRule],
                  id: item.id,
                }
                item.summarys.map(single => {
                  detail.summarayIds.push(single.summaryCode)
                })
                obj.voucherDetails.push(detail)
              })
              this.selectedVocherData.push(obj)
            }
          }
        })
      },
      getAssistsText(arr) {
        let text = []
        arr.map(item => {
          text.push(item.name)
        })
        return text + ''
      },
      // 选择关联费项
      selectExpense(data) {
        let tmpArr = []
        data.forEach(el => {
          tmpArr.push({
            'expenditure_id': el.code,
            'expenditure_name': el.name,
            'expenditure_type': el.type
          })
        })
        this.totalExpense = tmpArr
      },

      // 新增分录
      addVoucherItem(index) {
        this.selectedVocherData[index].voucherDetails.push({
          summarayIds: [], //摘要
          subjectId: [], //会计科目id
          fzhsText: '', //辅助核算文本
          borrowAmountRuleCode: [], // 借方金额规则字典code(借方)
          loanAmountRuleCode: [], // 贷方金额规则字典code(借方)
          superpositionRule: [], //金额叠加规则，PLUS正向(加)，MINUS逆向(减)
        })
      },
      // 选择会计科目时获取辅助核算
      selectSub(arr, index, one) {
        hlhttp.get({
          url: 'acct/accounting_subject/assists',
          data: {
            'subject_id': arr[0].code,
          },
          success: res => {
            if (!res.length) {
              this.selectedVocherData[index].voucherDetails[one].fzhsText
              return
            }
            let arr = []
            res.map(item => {
              arr.push(item.name)
            })
            this.selectedVocherData[index].voucherDetails[one].fzhsText = arr + ''
          }
        })
      },
      // 校验
      validate() {
        if (!this.bizTypeName) {
          hl.toast('业务场景不能为空')
          return false
        }
        if (this.bizCategoryCode == 'SKYW') {
          if (!this.standardActive.length) {
            hl.toast('业务标准不能为空')
            return false
          }
        }
        if (!this.selectedExpense.length) {
          hl.toast('关联费项不能为空')
          return false
        }
        if (!this.selectedReversalRule.length) {
          hl.toast('冲销规则不能为空')
          return false
        }
        if (!this.selectedVocherData.length) {
          hl.toast('请增加凭证')
          return false
        }

        for (var i = 0; i < this.selectedVocherData.length; i++) {
          let item = this.selectedVocherData[i]
          let Jarr = 0
          let Darr = 0
          if (!item.voucherTypeId.length) {
            hl.toast('请选择凭证类别')
            return false
          }
          for (let n = 0; n < item.voucherDetails.length; n++) {
            let single = item.voucherDetails[n]
            if (!single.summarayIds.length) {
              hl.toast('请选择摘要')
              return false
            }
            if (!single.subjectId.length) {
              hl.toast('请选择会计科目')
              return false
            }
            if (!single.borrowAmountRuleCode.length) {
              hl.toast('请选择借方金额')
              return false
            }
            if (!single.loanAmountRuleCode.length) {
              hl.toast('请选择贷方金额')
              return false
            }
            if (!single.superpositionRule.length) {
              hl.toast('请选择金额正负规则')
              return false
            }
            if (single.borrowAmountRuleCode + '' == '0') {
              Jarr++
            }
            if (single.loanAmountRuleCode + '' == '0') {
              Darr++
            }
          }
          if (!Jarr || !Darr) {
            hl.toast('一个凭证必须满足至少有一条借方金额与一条贷方金额')
            return false
          }
        }
        return true
      },
      // 保存凭证调
      addEditVoucherRule() {
        if (!this.validate()) return false
        let vocherData = []
        this.selectedVocherData.map(item => {
          item.voucherDetails.map(single => {
            let data = {
              voucher_type_id: item.voucherTypeId + '',
              summarays: [],
              subject_id: single.subjectId + '',
              borrow_amount_rule_code: single.borrowAmountRuleCode + '',
              loan_amount_rule_code: single.loanAmountRuleCode + '',
              superposition_rule: single.superpositionRule + '',
              id: single.id || '#'
            }
            let summarays = []
            single.summarayIds.map(one => {
              this.summaryData.map(el => {
                if (one == el.code) {
                  summarays.push({
                    summary_code: el.code,
                    summary_value: el.name
                  })
                }
              })
            })
            data.summarays = JSON.stringify(summarays)
            vocherData.push(data)
          })
        })
        const submitData = {
          'biz_category_code': this.bizCategoryCode || '#',
          'biz_type_name': this.bizTypeName || '#',
          'status': this.selectedVocherRuleState.join() || '#',
          'accounting_id': this.accountingId,
          'offset_rule_code': this.selectedReversalRule.join() || '#',
          'expenses': JSON.stringify(this.totalExpense),
          'details': JSON.stringify(vocherData),
          'biz_standard': this.bizCategoryCode == 'SKYW' ? (this.standardActive + '') : '#'
        }
        if (this.bizCategoryCode == 'SKYW' || this.bizCategoryCode == 'SRQR') {
          submitData.scene_type_code = this.selectedScene + ''
        }
        // if (this.bizCategoryCode == 'SKYW') {
        //   submitData.biz_standard = this.standardActive + '' || '#'
        // }
        if (this.voucherRulesId == null || this.voucherRulesId == 'null') {
          hlhttp.post({
            url: 'acct/voucher_rule',
            data: submitData,
            success: res => {
              hl.toast('添加成功')
              $('.finicial-doc-view-content').load('modules/system_config/page/finicial_voucher_rule_config_one.html')
              this.getVoucherRulesData()
            }
          })
        } else {
          submitData.id = this.voucherRulesId
          hlhttp.put({
            url: 'acct/voucher_rule',
            data: submitData,
            success: res => {
              hl.toast('编辑成功')
              $('.finicial-doc-view-content').load('modules/system_config/page/finicial_voucher_rule_config_one.html')
              this.getVoucherRulesData()
            }
          })
        }
      },
    }
  })
}())